package com.woniu.his.app.common.util;


import com.woniu.his.app.common.AppResultCode;
import com.woniu.his.exception.HisException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * @version: java version 1.8
 * @Author: Mr Ni
 * @description:
 * @date: 2022-09-21 17:29
 */
public class JwtUtil {

    private static String secrt = "nfoqufbnuqbfnuoqejbfouqenfiugwofnjfbsnxisdiwhdoqhwdiqwndiqwndoidqnoenfq";

    private static Integer defaultTime = 60;


    public static String create(Map<String, Object> maps, Integer time) {

        Key key = Keys.hmacShaKeyFor(secrt.getBytes());
        JwtBuilder builder = Jwts.builder();
        if (maps != null && maps.size() > 0) builder.setClaims(maps);
        if (time == null) time = defaultTime;
        builder.setExpiration(new Date(System.currentTimeMillis() + time * 60000));
        builder.signWith(key);
        return builder.compact();
    }


    public static String create(Map<String, Object> maps) {

        return create(maps, null);
    }

    public static String create(Integer time) {

        return create(null, time);
    }

    public static String create() {

        return create(null, null);
    }

    public static Claims parse(String token) {
        Key key = Keys.hmacShaKeyFor(secrt.getBytes());
        Claims body = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
        return body;
    }

    public static Integer getUserId(String token) {
        try {
            Claims parse = JwtUtil.parse(token);
            return (Integer) parse.get("userId");
        } catch (Exception e) {
            throw new HisException(AppResultCode.TOKEN_RESULT_CODE);
        }

    }

}
